import { DproHeader, DproLoading, DproEmpty } from "../components/index";
import { API_URLS } from '../api/index.js';
import DproContentItem from "../components-business/content-item/index.vue";
import DpSettingModal from "../components-business/dp-setting-modal/dp-setting-modal.vue";
import { requestApi, formatCardProps } from "../utils/util";
import widgetConfig from '../widget.config.json';
let propsConfig = Object.assign({}, widgetConfig.props);

Widget({
  props: {
    config: {
      type: String,
      default: () => {
        return JSON.stringify({
          isPub: 2,
          roleType: 2, // 2 企业主
          userId: '',
          accessToken: 'P9z3NsDgWpcJDLRndq5hqzueAXkAWJkR', // 业务token
        })
      }
    },
    card: {
      type: String,
      default: () => {
        return JSON.stringify({
          appId: "d474ee50",
          index: 1,
          screenId: "9AAFA5",
        })
      }
    }
  },
  components: { DproHeader, DproLoading, DproEmpty, DproContentItem, DpSettingModal },
  data() {
    return {
      widgetConfig,
      propsConfig,
      widgetData: {},
      rankList: [], // 告警排列序号,层级名称,告警数量
      activeIdx: 1,
      countTime: [{
        name: '日',
        type: 1
      }, {
        name: '周',
        type: 2
      }, {
        name: '月',
        type: 3
      }],
      deviceCodes: '',
      activeTimeType: 1,
      loading: false,
      ind: 0,
      cardInfo: {}
    };
  },
  // created() {
  //   // 浏览器本地调试注入wgt
  //   const script = document.createElement('script');
  //   script.src = 'https://dv.dlife.cn/digital/screen/preview/js/wgt-jssdk-1.0.3.js?t=1708564868451';
  //   script.async = true;
  //   script.onload = () => {
  //     WgtSDK.globalConfig({ clientId: 'devtools' })
  //   };
  //   document.head.appendChild(script);
  // },
  methods: {
    refresh(){
      this.getDataList()
    },
    // 获取格式化业务响应数据
    async getDataList() {
      requestApi({
        url: API_URLS.getDisputeWarningList,
        method: 'post',
        headers: {
          AccessToken: this.cardInfo.accessToken
        }
      }).then(res => {
        if (res.code === 0) {
          let dataObj = JSON.parse(res.data.res);
          for (let i = 0; i < dataObj.length; i++) {
            dataObj[i].alarmNo = i + 1;
            dataObj[i].caseBehavior = dataObj[i].caseBehavior.split('#').join('、');
          }
          this.rankList = dataObj;
        }
      })
    },
    setting() {
      this.$refs.settingModal?.open({});
    },
    // getCardDeviceInfo() {
    //   requestApi({
    //     url: API_URLS.getCardDeviceInfo,
    //     method: 'post',
    //     data: { screenId: this.cardInfo.screenId, cardId: this.cardInfo.cardId, cardSeq: this.cardInfo.index },
    //     headers: {
    //       AccessToken: this.cardInfo.accessToken
    //     }
    //   }).then(res => {
    //     if (res.code === 0) {
    //       if (res.data?.cardName) this.propsConfig.title = res.data.cardName
    //       this.deviceCodes = res.data?.deviceCodes
    //     }
    //     this.getDataList()
    //   })
    // },
    saveCardDeviceInfo(cardName = this.cardInfo.cardName, deviceCodes = '') {
      requestApi({
        url: API_URLS.saveCardDeviceInfo,
        method: 'post',
        data: { screenId: this.cardInfo.screenId, cardId: this.cardInfo.cardId, cardName, deviceCodes, cardSeq: this.cardInfo.index },
        headers: {
          AccessToken: this.cardInfo.accessToken
        }
      }).then(res => {
        if (res.code === 0) {
          wgt.showMessage({
            title: '配置成功',
            icon: 'success',
            duration: 3000
          });
          // this.getCardDeviceInfo()
          this.$refs.settingModal?.close();
        }
      }).catch(err => {
        wgt.showMessage({
          title: err.msg,
          icon: 'error',
          duration: 3000
        });
      })
    },
    getPopupContainer() {
      return this.$refs.absContainer;
    },
    handleChangeTime(idx) {
      this.activeTimeType = idx
      this.getCralData()
    },
    enter(el) {
      let delay = this.ind
      this.ind += 0.2
      el.style.animation = 'one-in 0.5s both'
      el.style.animationDelay = `${(delay).toFixed(1)}s`
    },
    openWin(deviceCode) {
      this.widgetConfig.routerConfig.deviceCode = deviceCode
      window.eventBus && window.eventBus.$emit('navigate-router', this.widgetConfig.routerConfig)
    },
    // 根据id获取接口配置信息
    getDataSourceById(id) {
      return this.widgetConfig.dataSource.find(it => it.id === id);
    },
    /**
     * 获取接口响应数据，支持动态接口(extraParam为业务扩展请求参数)和静态数据
     * @param {String} id 接口配置id，唯一标识
     * @param {Object} extraParam 业务扩展请求参数
     * @returns {Object} result
     *    result.type: 'api'动态接口请求模式，'static'静态数据
     *    result.data: 数据详情
     */
    async getDataSourceResult(id, extraParam = {}) {
      let conf = this.getDataSourceById(id);
      if (!conf) return { code: -2, msg: '缺少接口配置' };
      const { request = {}, data = {} } = conf;
      // 动态接口请求
      if (request.url) {
        const res = await requestApi({
          ...request,
          data: {
            ...(request.data || {}),
            ...extraParam
          },
          headers: {
            AccessToken: this.cardInfo.accessToken,
            ...(request.headers || {})
          }
        })
        return { type: 'api', data: res };
      } else {
        // 静态数据
        return { type: 'static', data };
      }
    },
  },
  mounted() {
    // 读取卡片props初始化参数并保存到配置文件中
    this.cardInfo = formatCardProps(this.$props, { cardName: this.propsConfig.title });

    // 每隔60s刷新数据
    window.eventBus && window.eventBus.$on('card-refresh-timer', this.getCralData)
    this.getDataList()
  },
  beforeDestroy() {
    window.eventBus && window.eventBus.$off('card-refresh-timer', this.getCralData)
  },
});